import { Store, createStore } from "vuex"
import { InjectionKey } from "vue"
import { login as loginApi, loginOut as loginOutApi } from "@mars/common/api/modules/user"
import { getToken, removeToken, setToken } from "@mars/utils/auth"
import defAva from "@mars/assets/image/profile.jpg"
import { LoginData } from "../api/modules/type"
import to from "await-to-js"
export interface User {
  token: string;
  name: string;
  nickname: string;
  userId: string | number;
  avatar: string;
  roles: Array<string>;
  permissions: Array<string>;
}


const store = createStore<User>({
  state: {
    token: getToken(),
    name: "",
    nickname: "",
    userId: "",
    avatar: "",
    roles: [],
    permissions: []
  },

  mutations: {
    setToken(state, token: string) {
      state.token = token
      setToken(token)
    },
    setUserInfo(state, userInfo: any) {
      state.name = userInfo.userName
      state.nickname = userInfo.nickName
      state.userId = userInfo.userId
      state.avatar = userInfo.avatar === "" || userInfo.avatar == null ? defAva : userInfo.avatar
    },
    clearUser(state) {
      state.token = ""
      state.name = ""
      state.nickname = ""
      state.userId = ""
      state.avatar = ""
      state.roles = []
      state.permissions = []
      removeToken()
    }
  },
  actions: {
    async login({ commit }, userInfo: LoginData): Promise<any> {
      const [err, res] = await to(loginApi(userInfo))
      console.log("err=====", err, res)
      if (res) {
        const data = res.data
        commit("setToken", data.access_token)
        // 确保 token 已写入 localStorage
        await new Promise(resolve => setTimeout(resolve, 0))
        return res
      }
      return Promise.reject(err)
    },

    async logout({ commit }): Promise<void> {
      await loginOutApi()
      commit("clearUser")
    }
  }

})

export const useUserStore = () => store
